package org.dreamwork.tools.code.analyzer.core.managed;

import org.dreamwork.concurrent.broadcast.LocalBroadcaster;
import org.dreamwork.injection.IInjectResolvedProcessor;
import org.dreamwork.injection.IObjectContext;
import org.dreamwork.tools.code.analyzer.core.data.Schema;
import org.dreamwork.tools.code.analyzer.core.data.SystemConfig;
import org.dreamwork.tools.code.analyzer.core.service.ISystemConfigService;
import org.dreamwork.tools.code.analyzer.core.util.Const;
import org.dreamwork.util.StringUtil;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Resource
public class LocalConfig implements IInjectResolvedProcessor {
    private final SystemSettings settings = new SystemSettings ();

    private final ExecutorService executor = Executors.newCachedThreadPool ();

    private LocalBroadcaster broadcaster;

    @Resource
    private ISystemConfigService service;

    @Resource
    public SystemSettings getSystemSettings () {
        return settings;
    }

    @Resource
    public LocalBroadcaster getBroadcaster () {
        if (broadcaster == null) {
            broadcaster = new LocalBroadcaster (executor);
        }
        return broadcaster;
    }

    @PostConstruct
    public void registerDatabaseSchemas () {
        Schema.registerAllSchemas ();
    }

    @PreDestroy
    public void destroy () {
        if (broadcaster != null) {
            broadcaster.shutdownNow ();
        }
        executor.shutdownNow ();
    }

    @Override
    public void perform (IObjectContext context) {
        List<SystemConfig> configs = service.all (SystemConfig.class);
        if (configs != null && !configs.isEmpty ()) {
            Map<String, SystemConfig> dict = configs.stream().collect (Collectors.toMap (SystemConfig::getId, c -> c));
            SystemConfig conf = dict.get (Const.KEY_DEFAULT_IGNORED);
            if (conf != null && !StringUtil.isEmpty (conf.getValue ())) {
                settings.setIgnored (conf.getValue ());
            }
        }
    }
}